//
//  ZBLoginUserDM.m
//  ZBShoppingMall
//
//  Created by apple on 2018/9/15.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "ZB_LoginUserDM.h"
#import "AppCacheDataManger.h"
#import "AppDataConversionTool.h"


//用户id保存
#define SMLoginUserDMUserIdKey      @"SMLoginUserDMUserIdKey"
//用户信息保存
#define SMLoginUserDMUserinfoKey      @"SMLoginUserDMUserinfoKey"

@implementation ZB_LoginUserDM
- (ZB_LoginUserModel *)user
{
    return [ZB_LoginUserDM currentLoginUser];
}

- (BOOL)isLogin
{
    ZB_LoginUserModel *user =  [ZB_LoginUserDM currentLoginUser];
    return user.isLogin;
}
- (void)resetLoginOut
{
    self.user.loginStatus = ZB_LoginStatus_Logout;
    [self saveCurrentUserInfoToCacheWithUser:self.user];
}
@end

@implementation ZB_LoginUserDM(CacheExtension)

+ (ZB_LoginUserModel *)currentLoginUser
{
    ZB_LoginUserModel *user = [self obtainCurrentUserInfoToCache];
    if(user == nil){
        user = [[ZB_LoginUserModel alloc]init];
    }
    return user;
}

#pragma mark - 沙盒操作
+(void)saveCurrentUserToken:(NSString *)token;
{
    if(token.length == 0){
        NSLog(@"保存的userId 不能为nil");
        return;
    }
    [[AppCacheDataManger shareInstance] saveObject:token forKey:SMLoginUserDMUserIdKey];
}

+ (void)removeCurrentToken{
    [[AppCacheDataManger shareInstance] removeForKey:SMLoginUserDMUserIdKey];
}

+(NSString *)obtainCurrentUserToken
{
    NSString *userId  = (NSString *) [[AppCacheDataManger shareInstance] getObectForKey:SMLoginUserDMUserIdKey];
    return userId;
}



+ (ZB_LoginUserModel *)obtainCurrentUserInfoToCache
{
    NSDictionary *userDict = (NSDictionary *)[[AppCacheDataManger shareInstance] getObectForKey:SMLoginUserDMUserinfoKey];
    if(userDict){
        ZB_LoginUserModel *user = [[AppDataConversionTool shareInstance] convertWithDictionary:userDict ToModel:[ZB_LoginUserModel class]];
        return user;
    }else{
        return nil;
    }
}

- (void)saveCurrentUserInfoToCacheWithUser:(ZB_LoginUserModel *)user
{
    if(user == nil) return;
    NSDictionary *userDictionary = [[AppDataConversionTool shareInstance] convertWithModelToDictionary:user];
    //找出nil 的数据并移除
    NSMutableDictionary *saveDict = [userDictionary mutableCopy];
    NSArray *keysForNullValues = [saveDict allKeysForObject:[NSNull null]];
    [saveDict removeObjectsForKeys:keysForNullValues];
    
    //保存
    [[AppCacheDataManger shareInstance] saveObject:saveDict forKey:SMLoginUserDMUserinfoKey];
    
}

- (void)updateCurrentUserInfoToCacheWithUser:(ZB_LoginUserModel *)user
{
    [self saveCurrentUserInfoToCacheWithUser:user];
}

- (void)removeUserModel
{
    [[AppCacheDataManger shareInstance] removeForKey:SMLoginUserDMUserinfoKey];
}

@end
